<template>
  <div>
    <vxe-modal
      :title="modalTitle"
      v-model="show"
      :loading="loading"
      :mask="false"
      :lock-view="false"
      width="80vw"
      height="80vh"
      min-width="800px"
      destroy-on-close
      show-zoom
      remember
      resize
      show-footer
    >
      <!-- 主体部分： form 表单 -->
      <el-form
        ref="refForm"
        :model="formData"
        :rules="formRules"
        label-width="130px"
      >
        <el-tabs v-model="activeTab">
          <!-- 基本信息 -->
          <el-tab-pane
            :label="$t('menu.dev.field.tabs.base', '基本信息')"
            name="basic"
          >
            <!-- 基本配置 -->
            <BaseConfig
              v-model="formData"
              :dict-code-for-type="dictCodeForType"
              :common-input-style="commonInputStyle"
              @type-change="mergeDefaultConfig"
              @field-name-change="changeFieldName"
            />

            <!-- 字段配置 -->
            <FieldConfig
              v-model="formData"
              :common-input-style="commonInputStyle"
              :length-type="lengthType"
              @check-table-data="checkTableHasData"
            />

            <!-- 数据表配置 -->
            <GridConfig
              v-model="formData"
              :common-input-style="commonInputStyle"
            />

            <!-- 表单配置 -->
            <FormConfig
              ref="formConfigRef"
              v-model="formData"
              :common-input-style="commonInputStyle"
              :dict-type="dictType"
              :select-options="dictOptions"
              :validate-types="validateTypes"
              @select-type-change="changeSelectType"
              @select-upload-change="changeSelectUpload"
              @show-dict-dialog="showDictDialog"
            />

            <!-- 多语言配置 -->
            <LanguageConfig
              v-if="menuInfo.lang"
              v-model="formData"
              :language-list="languageList"
              @get-trans-data="getTransData"
            />
          </el-tab-pane>

          <!-- 扩展配置标签页 -->
          <el-tab-pane
            :label="$t('menu.dev.field.tabs.extend', '扩展信息')"
            name="extend"
            v-if="!isApi"
          >
            <div class="form-section">
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item-plus
                    :label="$t('menu.dev.field.field.config', '高级配置')"
                    prop="extend_config"
                    label-position="top"
                  >
                    <ra-object-editor v-model="formData.config.extend_config" />
                  </el-form-item-plus>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>

          <!-- 配置对象编辑 -->
          <el-tab-pane
            :label="$t('menu.dev.field.tabs.json_edit', '配置编辑')"
            name="json_edit"
            v-if="!isApi"
          >
            <div class="form-section">
              <ra-object-editor v-model="formData.config" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- footer -->
      <template #footer>
        <div>
          <el-button type="info" @click="cancelHandler">
            {{ $t('common.action.cancel', '取消') }}
          </el-button>
          <el-button type="warning" @click="resetHandler">
            {{ $t('common.action.reset', '重置') }}
          </el-button>
          <el-button type="primary" @click="submitHandler" :disabled="loading">
            {{ $t('common.action.confirm', '确定') }}
          </el-button>
        </div>
      </template>
    </vxe-modal>
    <add-dict
      ref="addDictRef"
      @reload="updateOption"
      :api="DictAPI"
      :options="selectOption"
    />
  </div>
</template>

<script setup>
// 设置选项式 API 的内容
defineOptions({
  name: 'DevFieldModalRefactored',
  inheritAttrs: false,
});

import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';
import DictAPI from '@/api/admin/admin/dict';
import FieldAPI from '@/api/admin/dev/field';
import LangAPI from '@/api/admin/admin/i18n';
import { clone } from 'xe-utils';
// import AddDict from './components/AddDict.vue';
import AddDict from '@/views/admin/admin/dict/add.vue';
import { useDictStore } from '@/store';

// 导入子组件
import BaseConfig from './components/BaseConfig.vue';
import FieldConfig from './components/FieldConfig.vue';
import GridConfig from './components/GridConfig.vue';
import FormConfig from './components/FormConfig.vue';
import LanguageConfig from './components/LanguageConfig.vue';

// Props定义
const props = defineProps({
  mode: {
    type: String,
    default: 'add',
    validator: (value) => ['add', 'update'].includes(value),
  },
});

// 定义可触发事件
const emit = defineEmits(['reload']);

// 当前路由对象
const route = useRoute();

// 响应式数据
const loading = ref(false);
const show = ref(false);
const activeTab = ref('basic');
const refForm = ref(null);
const addDictRef = ref(null);
const formConfigRef = ref(null);
const defaultConfigList = ref([]);
const languageList = ref([]);
const menuInfo = ref({});
const currentId = ref(null);
const dictStore = useDictStore();
const selectOption = ref({});
const dictOptions = ref([]);

// 计算属性：通用样式
const commonInputStyle = computed(() => ({ minWidth: '220px' }));

// 计算属性：模态框标题
const modalTitle = computed(() => {
  return props.mode === 'add'
    ? $t('common.action.add', '新增')
    : $t('common.action.update', '修改');
});

// 计算属性：字典代码
const dictCodeForType = computed(() => {
  return route.query.app === 'admin'
    ? 'sys_admin_form_options'
    : 'sys_api_form_options';
});

// 计算属性：是否为API
const isApi = computed(() => route.query.app === 'api');

// 常量数据
const lengthType = ref([
  'varchar',
  'bigint',
  'int',
  'smallint',
  'tinyint',
  'decimal',
]);

const dictType = ref([
  'select',
  'transfer',
  'radio',
  'checkbox',
  'tree_select',
  'switch',
]);

const validateTypes = ['input', 'textarea', 'password'];

// 表单数据
const formData = ref(createInitialFormData());

// 表单验证规则
const formRules = reactive({
  title: [
    {
      required: true,
      message: $p('menu.dev.field.field.title', '字段标题'),
      trigger: 'blur',
    },
  ],
  field: [
    {
      required: true,
      message: $p('menu.dev.field.field.field', '字段'),
      trigger: 'blur',
    },
    {
      pattern: /^[a-z_][a-z0-9_]+$/,
      message: $t(
        'common.message.validate.only_lower_under',
        '只能包含小写字母和下划线',
      ),
    },
  ],
});

// 工具函数
function createInitialFormData() {
  return {
    id: null,
    menu_id: null,
    title: null,
    translations: [],
    field: null,
    remark: null,
    sort: null,
    status: null,
    config: {
      type: null,
      create_field: null,
      field_belong: null,
      grid_visible: null,
      form_post: null,
      field_type: null,
      field_length: null,
      field_default: null,
      field_constraint: [],
      field_index: null,
      grid_render: null,
      grid_render_function: null,
      grid_search: null,
      grid_width: null,
      grid_token_render: null,
      grid_sortable: null,
      grid_filterable: null,
      grid_editable: null,
      item_multiple: 'checkbox',
      item_options: null,
      item_map: null,
      item_editor: null,
      item_image_upload: null,
      item_file_upload: null,
      item_max_count: 6,
      item_rows: null,
      item_random_length: null,
      item_sn_format: null,
      item_date_format: null,
      item_date_type: null,
      item_menu: null,
      item_required: null,
      item_default: null,
      item_placeholder: null,
      item_tooltip: null,
      item_when: null,
      item_validate: null,
      item_regular_type: null,
      item_regular_content: null,
      item_function_name: null,
      item_function_content: null,
      extend_config: {},
    },
  };
}

function showMessage(type, action) {
  const messageKey =
    type === 'success'
      ? 'common.message.success.general'
      : 'common.message.failed.general';

  ElMessage[type]($t(messageKey, { action: $t(action) }));
}

const resetForm = () => {
  if (refForm.value) {
    refForm.value.resetFields();
  }
};

const initFormData = (data = {}) => {
  Object.assign(formData.value, createInitialFormData(), data);
  console.log('initFormData', formData.value);
};

// 事件处理方法
const changeFieldName = async (field) => {
  try {
    const { data: key } = await FieldAPI.getLanguageKey({
      field,
      menu_id: formData.value.menu_id,
    });
    formData.value.key = key;
  } catch (error) {
    console.error('Error generating language key:', error);
  }
};

const getTransData = async () => {
  if (!formData.value.key) {
    ElMessage.error($p('menu.admin.lang.field.lang_key', '多语言键名'));
    return;
  }

  try {
    const { data } = await LangAPI.getTransData({ key: formData.value.key });
    formData.value.translations = data;
    showMessage('success', 'common.action.load');
  } catch (error) {
    console.error('Error loading translation data:', error);
  }
};

const updateOption = async () => {
  await dictStore.refreshDictionaryCache();
  dictOptions.value = await dictStore.getDictionary('dict_options');
};

const showDictDialog = async () => {
  selectOption.value = {
    level: [
      { label: '系统字典', value: 1 },
      { label: '用户字典', value: 2 },
    ],
    type: await dictStore.getDictionary('sys_dict_type'),
  };
  addDictRef.value?.show();
};

/**
 * 选中不同的类型后，载入默认设置时，保留哪些字段的值
 * @param type
 */
const mergeDefaultConfig = (type) => {
  const configDefault = defaultConfigList.value[type];
  // 添加时，使用默认设置
  if (props.mode === 'add') {
    if (configDefault) {
      const newConfig = JSON.parse(JSON.stringify(configDefault));
      // 添加操作，修改类型时，保留字段值
      const preservedData = {
        menu_id: formData.value.menu_id,
        title: formData.value.title,
        field: formData.value.field,
      };
      formData.value = { ...newConfig, ...preservedData };
    } else {
      formData.value = {};
    }
  } else {
    if (configDefault) {
      const newConfig = JSON.parse(JSON.stringify(configDefault));
      // 修改操作，修改类型时，保留字段值
      const preservedData = {
        id: formData.value.id,
        menu_id: formData.value.menu_id,
        title: formData.value.title,
        field: formData.value.field,
        sort: formData.value.sort,
        status: formData.value.status,
        // ... 其他需要保留的字段
      };
      formData.value = { ...newConfig, ...preservedData };
    } else {
      formData.value = {};
    }
  }
};

const checkTableHasData = async () => {
  try {
    if (formData.value.menu_id && formData.value.field) {
      const { data: count } = await FieldAPI.checkTableHasData({
        menu_id: formData.value.menu_id,
        field: formData.value.field,
      });
      if (count > 0) {
        ElMessageBox.alert(
          $t(
            'menu.dev.field.tip.data_exists',
            '如果数据库表中已存在数据，请自行检查数据是否符合长度要求，否则会导致数据库同步操作失败',
          ),
          $t('common.title.warning', '警告'),
          { type: 'warning' },
        );
      }
    }
  } catch (error) {
    console.error('Error checking table data:', error);
  }
};

const changeSelectType = (type) => {
  if (type === 'multiple') {
    formData.value.config.field_type = 'json';
    formData.value.config.field_length = null;
  } else if (type === 'single') {
    formData.value.config.field_type = 'int';
    formData.value.config.field_length = 11;
  }
};
const changeSelectUpload = (type) => {
  if (
    type === 'ra-upload-card-multiple' ||
    type === 'ra-upload-list-multiple' ||
    type === 'ra-upload-list-multiple'
  ) {
    formData.value.config.field_type = 'json';
    formData.value.config.field_length = null;
  } else {
    formData.value.config.field_type = 'varchar';
    formData.value.config.field_length = 200;
  }
};

// 主要操作方法
const submitHandler = async () => {
  try {
    // 自动生成语言键
    if (!formData.value.key) {
      const { data: key } = await FieldAPI.getLanguageKey({
        field: formData.value.field,
        menu_id: formData.value.menu_id,
      });
      formData.value.key = key;
    }

    await refForm.value.validate();
    loading.value = true;

    const postData = clone(formData.value);
    console.log('Form Data:', postData);

    if (props.mode === 'add') {
      await FieldAPI.add(postData);
      // showMessage('success', 'common.action.add');
    } else {
      await FieldAPI.update(postData);
      // showMessage('success', 'common.action.update');
    }

    resetForm();
    show.value = false;
    emit('reload');
  } catch (error) {
    console.error(`Error in ${props.mode}Handler:`, error);
  } finally {
    loading.value = false;
  }
};

const cancelHandler = () => {
  resetForm();
  show.value = false;
};

const resetHandler = () => {
  resetForm();
};

// 优化后的约束和索引联动逻辑
watch(
  () => [
    formData.value.config.field_constraint,
    formData.value.config.field_index,
  ],
  ([newConstraint, newIndex], [oldConstraint, oldIndex]) => {
    const hasUniqueConstraint = newConstraint?.includes('unique');
    const hadUniqueConstraint = oldConstraint?.includes('unique');

    // 当添加唯一约束时，自动设置唯一索引
    if (!hadUniqueConstraint && hasUniqueConstraint && newIndex !== 'unique') {
      formData.value.config.field_index = 'unique';
    }

    // 当移除唯一约束时，如果当前是唯一索引则改为无索引
    if (hadUniqueConstraint && !hasUniqueConstraint && newIndex === 'unique') {
      formData.value.config.field_index = 'none';
    }

    // 当设置唯一索引时，自动添加唯一约束
    if (
      oldIndex !== 'unique' &&
      newIndex === 'unique' &&
      !hasUniqueConstraint
    ) {
      formData.value.config.field_constraint = [
        ...(newConstraint || []),
        'unique',
      ];
    }

    // 当取消唯一索引时，移除唯一约束
    if (oldIndex === 'unique' && newIndex !== 'unique' && hasUniqueConstraint) {
      formData.value.config.field_constraint = (newConstraint || []).filter(
        (item) => item !== 'unique',
      );
    }
  },
  { deep: true },
);

const initModal = () => {
  show.value = true;
  activeTab.value = 'basic';
  nextTick(() => {
    refForm.value?.clearValidate();
  });
};

// 暴露方法
defineExpose({
  async show(id) {
    dictOptions.value = await dictStore.getDictionary('dict_options');
    const { data } = await FieldAPI.initFieldForm({
      menu_id: route.query.id,
    });

    languageList.value = data.languages;
    defaultConfigList.value = data.field_default;
    menuInfo.value = data.menu_info;

    if (props.mode === 'add') {
      initFormData();
      formData.value.menu_id = route.query.id;
    } else {
      const { data } = await FieldAPI.getFormData({ id });
      currentId.value = id;
      initFormData(data);
    }
    initModal();
  },
});
</script>

<style lang="scss" scoped>
.form-section {
  margin: 5px;
  border: 1px solid #dcdfe6;
  padding: 5px;
  border-radius: 4px;
}
</style>
